/* eslint-disable no-extend-native */

import Big from './big.js';
const { Lang } = require('@app/lang');

// 翻译方法
String.prototype.LANG = function (params) {
  try {
    let translate = Lang.getGlobalLanguage(this) || this;
    if (translate && Object.prototype.toString.call(params) === '[object Object]') {
      for (let [key, val] of Object.entries(params)) {
        translate = translate.replace(new RegExp(`{${key}}`, 'g'), val);
      }
    }
    if (/____\d+$/.test(translate)) {
      translate = translate.replace(/____\d+$/, '');
    }
    return translate?.replace(/^[\b]*/, '');
  } catch (error) {
    console.log(error);
    return '';
  }
};

/**
 * @param digit - 位数
 * @return {String}
 */
String.prototype.toFixed = function (digit) {
  if (isNaN(Number(this))) {
    return this;
  } else {
    if (/e/i.test(this)) {
      return Number(this).toFixed();
    }
    if (this.includes('.') && digit === undefined) {
      digit = this.split('.')[1].length;
    }
    return Number(this).toFixed(digit);
  }
};

/**
 * @param digit - 位数
 * @return {String}
 */
String.prototype.toFormat = function (digit = 2) {
  if (isNaN(Number(this))) {
    return this;
  } else {
    if (this.includes('.') && digit === 'all') {
      digit = this?.toFixed()?.split('.')?.[1]?.length;
    }
    return Number(this).toFormat(digit);
  }
};

// 加法
String.prototype.add = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.plus(b).toNumber();
  } catch {
    return Number(this) + Number(arg);
  }
};

// 减法
String.prototype.sub = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.minus(b).toNumber();
  } catch {
    return Number(this) - Number(arg);
  }
};

// 乘法
String.prototype.mul = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.times(b).toNumber();
  } catch {
    return Number(this) * Number(arg);
  }
};

// 除法
String.prototype.div = function (arg) {
  try {
    const a = new Big(this);
    const b = new Big(arg);
    return a.div(b).toNumber();
  } catch {
    return Number(this) / Number(arg);
  }
};

// 公式计算
String.prototype.calc = function (obj, description) {
  try {
    let str = this.replace(/\s/g, '')
      .replace(/\+/g, '.add')
      .replace(/\-/g, '.sub')
      .replace(/\*/g, '.mul')
      .replace(/\//g, '.div');
    Object.entries(obj).forEach(([key, val]) => (str = str.replace(new RegExp(key, 'g'), `(${val})`)));
    if (description) console.log(description, str);
    return eval(str);
  } catch {
    return 0;
  }
};
